<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Biometric extends User_Controller
{
	private $response = array();
	private $userModel;
	//private $clientModel;
    public function __construct()
    {
        parent::__construct();
        $this->userModel = $this->load->model('User_Model');
        $this->clientModel = $this->load->model('Client_Model');
        //$this->payrollModel = $this->load->model('Payroll_Model');
        $this->timesheetModel = $this->load->model('Timesheet_Model');
        $this->biometricModel = $this->load->model('Biometric_Model');
        $this->dbGeneric = $this->load->model('Dbgeneric_Model');
        $this->load->helper('RequestManager');
        $this->requestManager = RequestManager::getInstance();
        $this->settings = $this->config->item('settings');
        $this->load->helper(array('ErrorConstants'));
        
    }

	public function fileList($api){
		$data = array();
		$result = $this->biometricModel->getFileList($api);
		if($result != 0 ){
			$response["message"] = "success";
			$response["data"] = $result;
			
		} else {
			$response["message"] = "error";
		}
		$data["response"] = ObjectUtils::arrayToJSON($response);
		$this->load->view('index', $data);
	}
	
	public function upload($api){
		
		if($this->input->post()) {
			$params = $this->input->post();
			//$response["data"] = $params;
			$return = $this->dbGeneric->saveOrUpdate('biometric_files', $params, 'id');
			if($return === true){
				$response["message"] = "success";
			}elseif($return > 0){
				$response["message"] = "success";
				$response["last_id"] = $return;
			}else{
				$response["message"] = "error";
			}
		}else{
			$response["message"] = "error";
		}
		$data["response"] = ObjectUtils::arrayToJSON($response);
		$this->load->view('index', $data);
	}
	
	public function view($api,$id,$user_id){
		
		if(is_numeric($id) && is_numeric($user_id)){
			$info = $this->biometricModel->find($api,$id,$user_id);
			if(isset($info)){
				$response['data'] = $info[0]; 
			}
			
			$response["message"] = "success";
		}
		$data["response"] = ObjectUtils::arrayToJSON($response);
		$this->load->view('index', $data);
	}
	
	public function load($api,$bid,$user_id){
		$times_start = time();
		require_once $_SERVER['DOCUMENT_ROOT'].'/application/managers/Excel_Reader.php';
		$this->load->helper(array('StringUtils','ConstantsUtils'));
		$data = array();
		$excel = Excel_Reader::getInstance();
		//$excel->setFilename($_SERVER['DOCUMENT_ROOT'] ."/timesheets/goji.xls");
		
		//Goji_June_30,_2012.xls
		
		$biofile = $this->biometricModel->find($api,$bid,$user_id);
		if(isset($biofile) && !empty($biofile)){
			$excel_file = $biofile[0]->file_name;
			//die($excel_file);
			$excel->setFilename($_SERVER['DOCUMENT_ROOT'] ."/timesheets/" . $excel_file);
			$data = $excel->read();
			$sheets = $data->sheets;
			$items = $sheets[0]['cells'];
			
			$client = $this->clientModel->find($api);
			$names = array();
			$member_name = "";
			
			foreach ($items as $item){
				//var_dump($item);
				if(strtolower($item[1]) == 'staff no.') {
					$username = strtolower(StringUtils::addUnderscore($item[5]));
					$employee_id = $item[2];
					$filter = array('client_id'=>$client->id, 'username'=>$username);
					$user = $this->userModel->find($filter);
					//var_dump($user);
					if(empty($user)) {
						$password='test';
						$info = array('username'=>urldecode($username),'password'=>CommonUtils::encryptPassword($password), 
						'client_id'=>$client->id, 'status'=>1,'is_active'=>1);
						$id = $this->User_Model->save($info);
						if($id > 0){
							// auto add file201 table
							$params = array();
							$params = array('user_id'=>$id, 'first_name'=>trim($item[5]),'employee_id'=>$employee_id);
							$this->dbGeneric->saveOrUpdate('file201',$params,'id');
							
							// auto add salary table
							$salary = 305;
							$hourly = floatval($salary) / ConstantsUtils::$EMPLOYEE_REGULAR_HOURS;
							$params = array();
							$params = array('user_id'=>$id, 'daily'=>$salary,'hourly'=>$hourly);
							
							$this->requestManager->setData($params);
							$this->requestManager->setSendType("post");
							$this->requestManager->setAccessPath($this->settings['api_path']."user/salary/$api");
							$return = $this->requestManager->send();
							
							
							//$this->dbGeneric->saveOrUpdate('file201',$params,'id');
							
							// auto add rest day table
							// default Sunday
							$params = array();
							$params = array('user_id'=>$id, 'day'=>'Sunday');
							$this->dbGeneric->saveOrUpdate('user_rest_day',$params,'user_id');
							
							$member_name = $username;
							$names["$member_name"]["user_id"] = $id;
						
						} 
					}else{
						$member_name = $user[0]->username;
						$names["$member_name"]["user_id"] = $user[0]->id;
					}
					//$member_name = $user[0]->username;
					//echo $username."<br>";
					//$names["$member_name"]["user_id"] = $user[0]->id;
					continue;
				} else if (strtolower($item[1])== "staff summary") {
					$names["$member_name"]['summary'] = $item;
					continue;
				} else if (strtolower($item[1])== "dept. summary") {
					$names["department"]['summary'] = $item;
					break;
				} else if(substr($item[1], 0, 4)== '2012') {
					//echo "adfasd";
					if($member_name != ""){
						$names["$member_name"]['logs'][] = $item;
					}
					//array_push($names["$member_name"]['logs'], $item);
					//$names["$member_name"]['logs'][count($names["$member_name"]['logs'])] = $item;
					continue;
				}
				
	
			}
			
			
			foreach($names as $key=>$name){
				if(isset($name["user_id"])){
					
				} else {
					continue;
				}
				
				$user_id = $name["user_id"];
				$logs = $name["logs"];
				$summary = $name["summary"];
				//echo "<p style='background-color:#f00'>Name: " . $key." ($user_id)</p>";
				
				foreach ($logs as $log) {
					$param = array();
					$date = substr(trim($log[1]),0,10);
					if(isset($log[6])) $ot = trim($log[6]);
					
					$time = (trim($log[3])!= "")?explode("  ", trim($log[3])):'';
					$absent = trim($log[9]);
					$late = trim($log[10]);
					$out_early = trim($log[11]);
					$early = trim($log[12]);
					if(isset($log[15])) 
						$remark = 	trim($log[15]);
					else 
						$remark = "";
	
					if($time != ''){
						if(count($time) == 2) {
							//echo "time in: " .$time[0].'<br>';
							//echo "time out: " .$time[1].'<br>';
							$param['time_in'] = "$date {$time[0]}";
							$param['time_out'] = "$date {$time[1]}";
							$param['bio_time_in'] = "$date {$time[0]}";
							$param['bio_time_out'] = "$date {$time[1]}";
						} else if (count($time) == 1){
							list($hr, $min) = explode(":",$time[0]);
							if(intval($hr) < 12 ) {
								//echo "time in: " .$time[0].'<br>';
								$param['time_in'] = "$date {$time[0]}";
								$param['time_out'] = "0000-00-00 00:00:00";
								$param['bio_time_in'] = "$date {$time[0]}";
								//echo "time out: -- <br>";
							} else {
								//echo "time in: -- <br>";
								//echo "time out: " .$time[0].'<br>';
								$param['time_in'] = "0000-00-00 00:00:00";
								$param['time_out'] = "$date {$time[0]}";
								$param['bio_time_out'] = "$date {$time[0]}";
							}
						}
					}
					
					$param['date'] = $date;
					//$param['absent']=  $absent;
					$late .= ($late != '')?":00":'00:00:00';
					$param['late'] = $late;
					$out_early .= ($out_early != '')?":00":'00:00:00';
					$param['undertime'] = $out_early;
					$param['bio_undertime'] = $out_early;
					$early .= ($early != '')?":00":'00:00:00';
					$param['earlier'] = $early;
					
					switch(strtolower($remark)){
						case 'absent':
							$remark_id = 1;
							break;
							
						case 'leave with pay':
							$remark_id = 2;
							break;
						
						case 'leave w/o pay':
							$remark_id = 3;
							break;
					
						case 'day off':
							$remark_id = 4;
							break;
							
						case 'wrong card':
							$remark_id = 5;
							break;
						
						case 'adjusted':
							$remark_id = 6;
							break;
							
						default:
							$remark_id = 7;
							break;
					}
					$param['remarks'] = $remark_id;
					$param['bio_remarks'] = $remark_id;
					$param['user_id'] = $user_id;
	
					//var_dump($param);
					$timesheet_id = $this->timesheetModel->save($param);
					//echo "<br>************************************<br>";
					
					
				}
			}
			
			// update biometric status
			
			//$this->dbGeneric->update(array('is_loaded'=>1),)
			$params = array();
			$params['id'] = $bid;
			$params['is_loaded'] = 1;
			$params['user_id'] = $this->session->userdata('user_id');
			
			$return = $this->dbGeneric->saveOrUpdate('biometric_files', $params, 'id');
			
			$time_end = time();
			$response["message"] = "success";
			$response["time"] = $time_end - $times_start;
			$info["response"] = ObjectUtils::arrayToJSON($response);
			$this->load->view('index', $info);
		} else {
			$response["message"] = "error";
			$info["response"] = ObjectUtils::arrayToJSON($response);
			$this->load->view('index', $info);
		}
		
	}
	
	
		
}